import Qs from 'qs'

export const getAllAddress = (vm) => {
  let data = vm.$store.state.userInfo.id
  vm.$axios.get('/permit/addresses/all/userId?userId=' + data)
    .then((res) => {
      vm.addressList = res.data.data
      vm.addressList.forEach(item => {
        item.province = JSON.parse(item.province)
      })
    })
}
export const updateAddress = (vm) => {

  let data = {
    address: vm.addressForm.address,
    id: vm.activeId,
    isDefault: vm.addressForm.isDefault ? 1 : 0,
    mobile: vm.addressForm.mobile,
    name: vm.addressForm.name,
    province: JSON.stringify(vm.addressForm.province),
    suserId: vm.$store.state.userInfo.id
  }
  vm.$axios.put('/permit/addresses/update', data)
    .then((res) => {
      if (res.data.code === 200) {
        vm.$message.success('修改成功')
        getAllAddress(vm)
      } else {
        vm.$message.error('修改失败')
      }
    })
}

export const addAddress = (vm) => {

  let data = {
    address: vm.addressForm.address,
    isDefault: vm.addressForm.isDefault ? 1 : 0,
    mobile: vm.addressForm.mobile,
    name: vm.addressForm.name,
    province: JSON.stringify(vm.addressForm.province),
    suserId: vm.$store.state.userInfo.id
  }
  vm.$axios.post('/permit/addresses', data)
    .then((res) => {
      vm.$message.success('添加成功')
      getAllAddress(vm)
    })
}

export const updateDefaultAddress = (vm) => {
  let data = Qs.stringify({
    AddressId: vm.activeId,
    userId: vm.$store.state.userInfo.id
  })
  vm.$axios.post('/permit/addresses/update/default', data)
    .then((res) => {
      console.log("修改成功")
    })
}

export const deleteAddress = (vm,addressId) => {
  let data = {
    addressId: addressId,
    userId: vm.$store.state.userInfo.id
  }
  vm.$axios.delete('/permit/addresses/delete', {params: data})
    .then((res) => {
      vm.$message.success('删除成功')
      getAllAddress(vm)
    })
}

export const getDefaultAddress = (vm) => {
  let data = Qs.stringify({
    userId: vm.$store.state.userInfo.id
  })
  vm.$axios.post('/permit/addresses/default', data)
    .then((res) => {
      console.log(res)
      res.data.data.province = JSON.parse(res.data.data.province)
      vm.addressDate = res.data.data
    })
}
